<template>
  <div class="container">
    <div class="head-top">
      <span>资产</span>
      <img @click="popupVisible=!popupVisible" src="static/img/qianbao.png" alt />
    </div>
    <div class="header flex-derc-warp" style="background-image: url(static/img/wallet_bg.png)">
      <div class="touxiang flex-derc-warp flex-center-center">
        <!-- <div class="imgTou flex-derc-warp flex-center-center">
          <img @click="$router.push({name:'EthWalletInfo'})" :src="account.img" alt="">
        </div>-->

        <div
          @click="$router.push({name:'EthWalletInfo'})"
          class="name flex-derc-warp flex-center-center"
        >
          <span>{{account.name}}</span>&nbsp;&nbsp;
        </div>

        <div
          @click="$router.push({name:'EthReceiptCode',params:{symbol:'ETH',path:'index'}})"
          class="yanzhengma flex-derc-warp flex-center-center"
        >
          <div
            style="width: 50%;text-overflow :ellipsis;overflow: hidden;display:inline-block;color:#fff;
          font-size:13px"
          >{{account.address}}</div>
          <div class="erweima flex-derc-warp flex-center-center">
            <img src="static/img/erweima.png" alt />
          </div>
        </div>
      </div>
      <div class="num">
        <div class="word">
          <span>总资产</span>
          <img src="static/img/eye.png" alt />
        </div>
        <div
          class="asset"
        >≈ {{parseFloat(this.currentAccount.balance?this.currentAccount.balance:0)}}</div>
      </div>
    </div>
    <div class="title">
      <span>Token list</span>
      <img src="static/img/addToken.png" @click="$router.push({name:'CoinList'})" alt />
    </div>
    <div style="position: absolute;left:46%;top:45%" v-if="isLoading">
      <van-loading type="spinner" color="#65686C" />
    </div>
    <div style="margin-bottom: 3.4375rem;">
      <coin
        :coin="{id:1027,name:'ETH',price:this.currentAccount.ethPrice,toMoney:(this.currentAccount.ethPrice*this.rate*(this.currentAccount.ethBalance / Math.pow(10,18))).toFixed(4),decimals:18,balance:this.currentAccount.ethBalance,img:'static/img/ETH.png'}"
      ></coin>

      <coin
        v-for="coin,index in switchCoins"
        :key="coin.id"
        :coin="{id:coin.id,name:coin.name,price:coin.price,decimals:coin.decimals,toMoney:((coin.balance / Math.pow(10,coin.decimals))*coin.price*rate).toFixed(4),balance:coin.balance,img:coin.img,decimals:coin.decimals,address:coin.contractaddress,abi:coin.abi}"
      ></coin>
      <!---->
    </div>

    <mt-popup
      v-model="popupVisible"
      position="right"
      popup-transition="popup-fade"
      style="width: 16.25rem;height: 100%;"
    >
      <div class="ethbox" v-if="wallet.length>0">
        <div class="slide-title">ETH钱包</div>

        <div class="ethWallet">
          <div
            class="w-block"
            :class="{active:index==accountIndex}"
            v-for="(account,index) in wallet"
            :key="index"
            @click="toggleWallet(index)"
          >
            <div class="wallet">
              <img src="static/img/ETH2.png" alt />&nbsp;&nbsp;
              <span>{{account.name}}</span>
            </div>
            <img v-if="index==accountIndex" class="r-img" src="static/img/w-right.png" alt />
            <img v-else class="r-img" src="static/img/b-right.png" alt />
          </div>
        </div>
      </div>
      <div class="createWallet" @click="$router.push({name:'EthCreateWallet'})">
        <img src="static/img/addWallet.png" alt />
        <span>创建钱包</span>
      </div>
    </mt-popup>

    <foot v-show="isOriginHeight" :index="$route.params.index?$route.params.index:1"></foot>
  </div>
</template>

<script>
import accountUtils from "../service/eth/accountUtils.js";
import web3Utils from "../service/eth/web3Utils.js";

import { ethMainNet } from "../service/eth/config";

import { mapGetters, mapActions } from "vuex";

import axios from "axios";
import Coin from "./eth/Coin";
import Foot from "./eth/Foot";
import { Popup } from "mint-ui";
import { Toast } from "vant";

export default {
  name: "Index",
  components: {
    Coin,
    Foot,
    Popup,
  },
  data() {
    return {
      isLoading: true,
      // index:this.$route.params.index?this.$route.params.index:1,
      popupVisible: false,
      rate: 0,
      value: "",
      switchCoins: [],
      contract: "",
      account: "",
      screenHeight: document.documentElement.clientHeight, // 当前高度
      originHeight: document.documentElement.clientHeight, //默认高度，用作比较
      isOriginHeight: false, //当前高度是否仍等于默认高度
    };
  },
  computed: {
    ...mapGetters([
      "wallet",
      "accountIndex",
      "coinsList",
      "currentAccount",
      "messageList",
      "ethBaseNet",
      "infuraAK",
    ]),
  },
  watch: {
    screenHeight(val) {
      if (this.originHeight - val > 60) {
        //这里以防万一改了下判断形式，当屏幕高度减少了60px以上时才隐藏footer
        this.isOriginHeight = false;
      } else {
        this.isOriginHeight = true;
      }
    },
  },
  created() {
    this.account = this.currentAccount;
  },
  methods: {
    ...mapActions([
      "setWallet",
      "setCoinsList",
      "setAccountIndex",
      "setCoinByIndex",
      "setEthBalance",
      "setEthPrice",
      "setBalance",
      "setWalletAccountByIndex",
    ]),
    async getRate() {
      let _this = this;
      await axios.get(_this.global.apiPath + "/rate/getRate").then((resp) => {
        _this.rate = parseFloat(resp.data.data.rate);
        _this.global.setRate(parseFloat(resp.data.data.rate));
      });
    },
    async getLastVersion() {
      let _this = this;
      await axios.get("http://8.210.42.153:8088/user/getEthInfo").then((resp) => {
        console.log(resp)
      });
    },
    //以太坊逻辑
    getCoinPrice() {
      let _this = this;
      axios.get(_this.global.apiPath + "/ticker/getLastTicker").then((resp) => {
        if (resp.status == 200 && resp.data) {
          for (let j = 0; j < resp.data.data.length; j++) {
            if (resp.data.data[j].symbol == "ETH") {
              _this.currentAccount.ethPrice = resp.data.data[j].priceUsd;
              continue;
            }
            for (let i = 0; i < _this.coinsList.length; i++) {
              if (_this.coinsList[i].name == resp.data.data[j].symbol) {
                _this.coinsList[i].price = resp.data.data[j].priceUsd;
                break;
              }
            }
          }
        }
      });
    },
    async getEthBalance() {
      let _this = this;
      let ethToMoney = 0;
      let coinMoney = 0;
      let asyncArr = [];
      if (!_this.currentAccount.coins) {
        _this.currentAccount.coins = [];
      }

      _this.switchCoins = [];
      for (let i = 0; i < _this.coinsList.length; i++) {
        if (_this.coinsList[i].open == true) {
          _this.switchCoins.push(_this.coinsList[i]);
        }
      }
      if (_this.rate == 0) {
        await this.getRate();
        await this.getLastVersion();
      }

      await this.getCoinPrice();

      // if (_this.switchCoins.length < 1) {
      //   coinflag = true;
      // }

      for (let i = 0; i < _this.switchCoins.length; i++) {
        let tokenCont = new _this.global.web3.eth.Contract(
          _this.switchCoins[i].abi,
          _this.switchCoins[i].contractaddress
        );
        asyncArr.push(
          tokenCont.methods.balanceOf(_this.currentAccount.address).call()
        );
      }
      asyncArr.push(
        _this.global.web3.eth.getBalance(_this.currentAccount.address)
      );

      let data = await _this.getData(asyncArr);

      Toast.clear();

      for (let i = 0; i < data.length - 1; i++) {
        _this.switchCoins[i].balance = data[i] > 0 ? data[i] : 0;
        coinMoney += parseFloat(
          (
            (data[i] / Math.pow(10, _this.switchCoins[i].decimals)) *
            parseFloat(_this.switchCoins[i].price) *
            _this.rate
          ).toFixed(4)
        );
      }
      let ethBal = data[data.length - 1];

      ethToMoney = parseFloat(
        (ethBal / Math.pow(10, 18)) * _this.currentAccount.ethPrice * _this.rate
      ).toFixed(4);
      _this.currentAccount.balance = (
        parseFloat(ethToMoney) + parseFloat(coinMoney)
      ).toFixed(4);
      _this.currentAccount.ethToMoney = ethToMoney;
      _this.currentAccount.ethBalance = ethBal;
      if (ethBal > 0) {
        _this.currentAccount.eth = _this.global.web3.utils.fromWei(
          ethBal + "",
          "ether"
        );
      } else {
        _this.currentAccount.eth = 0;
      }
      _this.isLoading = false;
    },
    async getData(asyncArr) {
      return Promise.all(asyncArr);
    },
    toggleWallet(index) {
      let _this = this;
      _this.popupVisible = false;
      // Toast.loading({
      //   duration: 0,
      //   forbidClick: true,
      //   message: 'loading...'
      // });
      _this.isLoading = true;
      _this.switchCoins = [];
      // _this.popupVisible = !_this.popupVisible

      _this.setAccountIndex(index);
      _this.account = _this.currentAccount;

      accountUtils
        .initWeb3FromPrivateKey(_this.account.priKey)
        .then(({ web3, provider, priKey, pubKey, address }) => {
          _this.global.setWeb3(web3);
          _this.getEthBalance();
        });
    },
    openScanCode() {
      this.$router.push({ name: "Scan" });
    },
  },
  async mounted() {
    window.onresize = () => {
      return (() => {
        this.screenHeight = document.documentElement.clientHeight;
      })();
    };
    let _this = this;

    if (!this.currentAccount) {
      this.$router.push({ name: "Welcome" });
    } else {
      await this.getCoinPrice();
      // Toast.loading({
      //   duration: 0,
      //   forbidClick: true,
      //   message: 'loading...'
      // });
      _this.isLoading = true;
      if (_this.global.web3 == "") {
        let fdStart = _this.currentAccount.priKey.indexOf("0x");
        if (fdStart != -1) {
          this.currentAccount.priKey = _this.currentAccount.priKey.substring(
            2,
            _this.currentAccount.priKey.length
          );
        }

        accountUtils
          .initWeb3FromPrivateKey(_this.currentAccount.priKey)
          .then(({ web3, provider, priKey, pubKey, address }) => {
            _this.global.setWeb3(web3);
            _this.getEthBalance();
          });
      } else {
        _this.getEthBalance();
      }
    }
  },
};
</script>
<style lang="less" scoped>
@import url("../assets/css/index.less");
</style>

